﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace RoyTools.ForegroundWindow.Domain
{
    /// <summary>
    /// 窗体辅助类
    /// </summary>
    public class FormHelper
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
        private static extern void SetForegroundWindow(IntPtr hwnd);

        /// <summary>
        /// 获取当前活动的窗体句柄
        /// </summary>
        public static IntPtr GetForegroundWindowHandle()
        {
            var foregroundWindow = Process.GetProcesses().ToList().SingleOrDefault(p => p.MainWindowHandle == GetForegroundWindow());
            return foregroundWindow == null ? IntPtr.Zero : foregroundWindow.MainWindowHandle;
        }

        /// <summary>
        /// 根据名称获取窗体句柄列表
        /// </summary>
        /// <param name="handleName"></param>
        /// <returns></returns>
        public static List<IntPtr> GetWindowHandlesByName(string handleName)
        {
            var windows = Process.GetProcesses().ToList().FindAll(p => { return string.Equals(p.ProcessName, handleName, StringComparison.CurrentCultureIgnoreCase); });
            var windowHandles = new List<IntPtr>();
            windows.ForEach(w => { windowHandles.Add(w.MainWindowHandle); });
            return windowHandles;
        }

        /// <summary>
        /// 根据handle设置活动窗体
        /// </summary>
        /// <param name="handle"></param>
        public static void SetForegroundWindowByHandle(IntPtr handle)
        {
            SetForegroundWindow(handle);
        }

        /// <summary>
        /// 获取所有窗体的句柄
        /// </summary>
        /// <returns></returns>
        public static List<string> GetAllWindowHandlesName()
        {
            var windowsHandlesName = new List<string>();
            Process.GetProcesses().ToList().ForEach(p => {
                windowsHandlesName.Add(p.ProcessName);
            });
            return windowsHandlesName;
        }

    }
}
